package com.hoolai.synroom.codec;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
import com.google.protobuf.GeneratedMessage;
import com.hoolai.synroom.config.CmdsConfig;
import com.hoolai.synroom.config.ReqCmdProperties;
import com.hoolai.synroom.dispatcher.SynRoomBusinessCommand;

public class ProtoBufDecoder extends OneToOneDecoder {

    private static Logger logger = Logger.getLogger("synfight");

    private final CmdsConfig CMDS_CONFIG;
    
    public ProtoBufDecoder(CmdsConfig cmdsConfig) {
        this.CMDS_CONFIG = cmdsConfig;
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
        if (!(msg instanceof ChannelBuffer)) {
            return msg;
        }
        ChannelBuffer buf = (ChannelBuffer) msg;
        if (buf.hasArray()) {
            int cmdIndex = buf.readByte() & 0xff;
            ReqCmdProperties cmdProperties = CMDS_CONFIG.getReqCmds()[cmdIndex];
            
            if(cmdProperties == null) {
                logger.warn("receive msg meet an unsupport cmd index:" + cmdIndex);
                return null;
            }
            
            GeneratedMessage proto = (GeneratedMessage) cmdProperties.getDefaultInstance().newBuilderForType()
                    .mergeFrom(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes()).build();
            SynRoomBusinessCommand businessCommand = new SynRoomBusinessCommand(cmdProperties, proto);

            logger.debug("------------------------------receive msg----------------------------------");
            logger.debug(businessCommand.getProto().toString());
            logger.debug("------------------------------receive msg end----------------------------------");
            return businessCommand;
        } else {
            logger.warn("receive msg meet a null buf");
        }
        return null;
    }

}
